# -*- coding: utf-8 -*-
"""
随访记录API接口
"""

from flask import Blueprint, request, jsonify, send_file
from datetime import datetime
import json
import pandas as pd
from io import BytesIO

# 确保所有模型都正确导入和初始化
from backend.models.student import Student
from backend.models.followup import FollowupRecord
from backend.models.followup_log import FollowupRecordLog
from backend.config.config_manager import ConfigManager
import logging

from backend.infrastructure.database import db

# 创建蓝图
followup_api = Blueprint("followup_api", __name__, url_prefix='/api/followup_records')

# 初始化配置管理器
config_manager = ConfigManager()

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)s %(message)s'
)

@followup_api.route('/list', methods=['GET'])
def list_records():
    """获取随访记录列表（直接查询随访表，确保包含id字段）"""
    try:
        student_id = request.args.get('student_id', type=int)
        logging.info(f"随访记录列表查询 - student_id: {student_id}")
        
        if student_id:
            # 针对特定学生查询随访记录，直接查询随访表
            records = FollowupRecord.query.filter_by(student_id=student_id)\
                .order_by(FollowupRecord.created_at.desc()).all()
            
            # 转换为字典格式，确保包含id字段
            results = []
            for record in records:
                record_dict = record.to_dict()
                
                # 添加学生基本信息（用于历史表显示）
                student = Student.query.get(record.student_id)
                if student:
                    record_dict.update({
                        'education_id': student.education_id,
                        'school': student.school,
                        'class_name': student.class_name,
                        'name': student.name,
                        'gender': student.gender
                    })
                    
                    # 添加扩展信息（如年级）
                    from backend.models.student_extension import StudentExtension
                    extension = StudentExtension.query.filter_by(student_id=student.id)\
                        .order_by(StudentExtension.data_year.desc()).first()
                    if extension:
                        record_dict['grade'] = extension.grade
                
                results.append(record_dict)
            
            logging.info(f"返回学生 {student_id} 的随访记录，共 {len(results)} 条")
            return jsonify({"success": True, "data": results})
            
        else:
            # 查询所有有随访记录的学生，使用统一查询服务
            from backend.api.query_api import build_smart_query_v2, format_query_results_v2
            from sqlalchemy import exists
            from backend.config.constants_v2 import CONFIG_REGISTRY
            
            history_fields = CONFIG_REGISTRY.get("FOLLOWUP_HISTORY_FIELDS", [])
            
            # 构建查询条件：只查询有随访记录的学生
            conditions = [exists().where(FollowupRecord.student_id == Student.id)]
            
            # 使用统一查询服务
            query, field_table_map = build_smart_query_v2(history_fields, conditions)
            results = query.all()
            
            # 使用统一结果格式化
            formatted_results = format_query_results_v2(results, history_fields, field_table_map)
            
            logging.info(f"返回所有有随访记录的学生，共 {len(formatted_results)} 条")
            return jsonify({"success": True, "data": formatted_results})
        
    except Exception as e:
        logging.error(f"获取随访记录列表失败: {e}", exc_info=True)
        return jsonify({"success": False, "error": str(e)}), 500

@followup_api.route('', methods=['POST'])
def create_followup():
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "error": "请求数据不能为空"}), 400
        
        print(f"📋 创建随访记录请求数据: {data}")
        
        # 使用配置驱动的字段映射（移除所有旧字段兼容）
        field_mapping = config_manager.get_followup_field_mapping()
        print(f"🔧 字段映射: {field_mapping}")
        
        mapped_data = {'student_id': data.get('student_id')}
        
        # 纯配置驱动的字段映射处理
        for frontend_field, backend_field in field_mapping.items():
            if frontend_field in data and data[frontend_field] is not None:
                mapped_data[backend_field] = data[frontend_field]
        
        print(f"📊 映射后数据: {mapped_data}")
        
        # 使用配置驱动的默认值设置
        if not mapped_data.get('contact_method'):
            from backend.config.constants_v2 import GLOBAL_OPTIONS_CONFIG
            default_contact_method = GLOBAL_OPTIONS_CONFIG.get('contact_method_options', ['电话'])[0]
            mapped_data['contact_method'] = default_contact_method
        if not mapped_data.get('followup_type'):
            from backend.config.constants_v2 import GLOBAL_OPTIONS_CONFIG
            default_followup_type = GLOBAL_OPTIONS_CONFIG.get('followup_type_options', ['常规随访'])[0]
            mapped_data['followup_type'] = default_followup_type
        
        print(f"✅ 最终数据: {mapped_data}")
        
        record = FollowupRecord(**mapped_data)
        db.session.add(record)
        db.session.commit()
        
        # 修复日志记录：新建记录应该是CREATE操作，old_content为None
        log = FollowupRecordLog(
            record_id=record.id,
            student_id=record.student_id,
            action='CREATE',
            operator=record.interviewer or "系统",
            old_content=None,  # 新建记录没有旧内容
            new_content=json.dumps(record.to_dict(), ensure_ascii=False),
            created_at=datetime.now()
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({"success": True, "data": record.to_dict()})
        
    except Exception as e:
        print(f"❌ 创建随访记录失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({"success": False, "error": f"创建失败: {str(e)}"}), 500

@followup_api.route('/<int:record_id>', methods=['PUT'])
def update_followup(record_id):
    record = FollowupRecord.query.get_or_404(record_id)
    data = request.json
    if not data:
        return jsonify({"success": False, "error": "请求数据不能为空"}), 400
    
    logging.info(f"更新随访记录 {record_id}，接收到的数据: {data}")
    
    old_data = record.to_dict()
    
    # 使用配置驱动的字段更新
    field_mapping = config_manager.get_followup_field_mapping()
    logging.info(f"字段映射: {field_mapping}")
    
    updated_fields = []
    for frontend_field, backend_field in field_mapping.items():
        if frontend_field in data:
            old_value = getattr(record, backend_field, None)
            new_value = data[frontend_field]
            setattr(record, backend_field, new_value)
            updated_fields.append(f"{frontend_field}: {old_value} -> {new_value}")
            logging.info(f"更新字段 {frontend_field}: {old_value} -> {new_value}")
    
    logging.info(f"总共更新了 {len(updated_fields)} 个字段: {updated_fields}")
    
    db.session.commit()
    
    # 修复日志记录：更新操作应该是UPDATE，保留完整的旧内容
    log = FollowupRecordLog(
        record_id=record.id,
        student_id=record.student_id,
        action='UPDATE',
        operator=record.interviewer or "系统",
        old_content=json.dumps(old_data, ensure_ascii=False),
        new_content=json.dumps(record.to_dict(), ensure_ascii=False),
        created_at=datetime.now()
    )
    db.session.add(log)
    db.session.commit()
    
    logging.info(f"随访记录 {record_id} 更新完成")
    return jsonify({"success": True, "data": record.to_dict()})

@followup_api.route('/<int:record_id>', methods=['DELETE'])
def delete_followup(record_id):
    record = FollowupRecord.query.get_or_404(record_id)
    old_data = record.to_dict()
    db.session.delete(record)
    db.session.commit()
    
    # 修复日志记录：删除操作应该是DELETE
    log = FollowupRecordLog(
        record_id=record.id,
        student_id=record.student_id,
        action='DELETE',
        operator=record.interviewer or "系统",
        old_content=json.dumps(old_data, ensure_ascii=False),
        new_content=None,  # 删除记录没有新内容
        created_at=datetime.now()
    )
    db.session.add(log)
    db.session.commit()
    
    return jsonify({"success": True})

@followup_api.route('/logs', methods=['GET'])
def get_logs():
    record_id = request.args.get('record_id', type=int)
    logs = FollowupRecordLog.query.filter_by(record_id=record_id).order_by(FollowupRecordLog.created_at.desc()).all()
    return jsonify({"success": True, "data": [l.to_dict() for l in logs]})

@followup_api.route('/logs_all', methods=['GET'])
def get_all_logs():
    student_id = request.args.get('student_id', type=int)
    if not student_id:
        return jsonify({"success": False, "error": "缺少student_id"}), 400
    logs = FollowupRecordLog.query.filter_by(student_id=student_id).order_by(FollowupRecordLog.created_at.desc()).all()
    return jsonify({"success": True, "data": [l.to_dict() for l in logs]})

@followup_api.route('/restore', methods=['POST'])
def restore_followup():
    """使用统一日志服务恢复随访记录"""
    try:
        from backend.services.unified_log_service import log_service
        
        data = request.json
        print(f"📋 恢复请求数据: {data}")
        
        if not data:
            print("❌ 请求数据为空")
            return jsonify({"success": False, "error": "请求数据不能为空"}), 400
        
        log_id = data.get('log_id')
        if not log_id:
            print("❌ 缺少log_id参数")
            return jsonify({"success": False, "error": "缺少log_id参数"}), 400
        
        print(f"🔄 开始恢复，log_id: {log_id}")
        
        # 使用统一日志服务进行恢复
        response, status_code = log_service.restore_record(
            LogModel=FollowupRecordLog,
            RecordModel=FollowupRecord,
            log_id=log_id,
            operator=data.get('operator', '系统'),
            ip_address=request.remote_addr
        )
        
        print(f"📊 恢复结果: status_code={status_code}, response={response}")
        
        return jsonify(response), status_code
        
    except Exception as e:
        print(f"❌ 随访记录恢复失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({"success": False, "error": f"恢复失败: {str(e)}"}), 500

@followup_api.route('/<int:record_id>', methods=['GET'])
def get_followup_record(record_id):
    record = FollowupRecord.query.get_or_404(record_id)
    return jsonify({"success": True, "data": record.to_dict()})

@followup_api.route('/config', methods=['GET'])
def get_followup_config():
    """获取随访记录配置接口"""
    try:
        return jsonify({
            "success": True,
            "config": config_manager.get_followup_config()
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"配置加载失败: {str(e)}"
        }), 500

@followup_api.route('/export', methods=['GET'])
def export_followup_records():
    student_id = request.args.get('student_id', type=int)
    export_type = request.args.get('type', 'xlsx')
    if not student_id:
        return jsonify({"success": False, "error": "缺少student_id"}), 400
    
    student = Student.query.get(student_id)
    student_name = student.name if student and student.name else "未知学生"
    title = f"{student_name}随访记录表"
    
    records = (FollowupRecord.query
               .filter_by(student_id=student_id)
               .order_by(FollowupRecord.followup_date.desc())
               .all())
    
    data = [r.to_dict() for r in records]
    if not data:
        return jsonify({"success": False, "error": "无数据"}), 404
    
    df = pd.DataFrame(data)
    
    # 使用配置化的导出字段（全局唯一配置驱动，无兜底）
    try:
        table_columns = config_manager.get_followup_table_columns()
        export_fields = [col["field"] for col in table_columns]
        column_rename_map = {col["field"]: col["label"] for col in table_columns}
    except Exception as e:
        return jsonify({"success": False, "error": f"导出配置加载失败: {str(e)}"}), 500
    
    # 确保字段存在
    available_fields = [field for field in export_fields if field in df.columns]
    df_export = df[available_fields].rename(columns=column_rename_map)  # type: ignore

    output = BytesIO()
    filename = f"{student_name}_随访记录.{'csv' if export_type == 'csv' else 'xlsx'}"
    
    if export_type == 'csv':
        df_export.to_csv(output, index=False, encoding='utf-8-sig')
        output.seek(0)
        return send_file(output, mimetype="text/csv", as_attachment=True, download_name=filename)
    else:
        with pd.ExcelWriter(output, engine='openpyxl') as writer:  # type: ignore
            pd.DataFrame([[title]]).to_excel(writer, sheet_name='Sheet1', index=False, header=False, startrow=0)
            df_export.to_excel(writer, sheet_name='Sheet1', index=False, header=True, startrow=1)
        output.seek(0)
        return send_file(output, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                         as_attachment=True, download_name=filename)

@followup_api.route('/<int:record_id>/export_excel', methods=['GET'])
def export_single_followup_record_excel(record_id):
    """
    导出单条随访记录为Excel格式
    前端显示名：导出当前随访记录
    """
    try:
        # 获取随访记录
        record = FollowupRecord.query.get_or_404(record_id)
        
        # 获取学生信息
        student = Student.query.get_or_404(record.student_id)
        student_name = student.name if student and student.name else "未知学生"
        title = f"{student_name}随访记录详情"
        
        # 将单条记录转换为数据格式
        data = [record.to_dict()]
        df = pd.DataFrame(data)
        
        # 使用配置化的导出字段
        try:
            table_columns = config_manager.get_followup_table_columns()
            export_fields = [col["field"] for col in table_columns]
            column_rename_map = {col["field"]: col["label"] for col in table_columns}
        except Exception as e:
            return jsonify({"success": False, "error": f"导出配置加载失败: {str(e)}"}), 500
        
        # 确保字段存在
        available_fields = [field for field in export_fields if field in df.columns]
        df_export = df[available_fields].rename(columns=column_rename_map)
        
        output = BytesIO()
        filename = f"{student_name}_随访记录_{record_id}.xlsx"
        
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            pd.DataFrame([[title]]).to_excel(writer, sheet_name='Sheet1', index=False, header=False, startrow=0)
            df_export.to_excel(writer, sheet_name='Sheet1', index=False, header=True, startrow=1)
        output.seek(0)
        
        return send_file(output, 
                        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        as_attachment=True, 
                        download_name=filename)
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'导出失败：{str(e)}'}), 500

@followup_api.route('/<int:record_id>/export_csv', methods=['GET'])
def export_single_followup_record_csv(record_id):
    """
    导出单条随访记录为CSV格式
    前端显示名：导出当前随访记录CSV
    """
    try:
        # 获取随访记录
        record = FollowupRecord.query.get_or_404(record_id)
        
        # 获取学生信息
        student = Student.query.get_or_404(record.student_id)
        student_name = student.name if student and student.name else "未知学生"
        
        # 将单条记录转换为数据格式
        data = [record.to_dict()]
        df = pd.DataFrame(data)
        
        # 使用配置化的导出字段
        try:
            table_columns = config_manager.get_followup_table_columns()
            export_fields = [col["field"] for col in table_columns]
            column_rename_map = {col["field"]: col["label"] for col in table_columns}
        except Exception as e:
            return jsonify({"success": False, "error": f"导出配置加载失败: {str(e)}"}), 500
        
        # 确保字段存在
        available_fields = [field for field in export_fields if field in df.columns]
        df_export = df[available_fields].rename(columns=column_rename_map)
        
        output = BytesIO()
        filename = f"{student_name}_随访记录_{record_id}.csv"
        
        df_export.to_csv(output, index=False, encoding='utf-8-sig')
        output.seek(0)
        
        return send_file(output, 
                        mimetype="text/csv", 
                        as_attachment=True, 
                        download_name=filename)
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'导出失败：{str(e)}'}), 500

@followup_api.route('/api/config/followup_result_fields', methods=['GET'])
def get_followup_result_fields():
    """
    返回随访主表所有字段（含虚拟字段）及其配置，供前端表格渲染使用。
    """
    try:
        # 获取主表字段配置
        followup_fields = config_manager.get_config("FOLLOWUP_SEARCH_RESULT_FIELDS", [])
        # 获取虚拟字段配置
        from backend.config.constants_v2 import CONFIG_REGISTRY, ALL_FIELD_CONFIG_REGISTRY
        virtual_fields = CONFIG_REGISTRY.get("VIRTUAL_FIELD_REGISTRY", {})
        fields = []
        for f in followup_fields:
            if isinstance(f, dict):
                field_name = f.get("field")
                label = f.get("label") or f.get("display_name") or field_name
            else:
                field_name = f
                label = None
            # 判断是否虚拟字段
            if field_name in virtual_fields:
                # 强制label取虚拟字段配置表
                fields.append({
                    "field": field_name,
                    "label": virtual_fields[field_name].get("display_name", field_name),
                    "is_virtual": True
                })
            else:
                # 非虚拟字段，label取ALL_FIELD_CONFIG_REGISTRY
                field_cfg = ALL_FIELD_CONFIG_REGISTRY.get("followup_record", {}).get(field_name) \
                    or ALL_FIELD_CONFIG_REGISTRY.get("student", {}).get(field_name) \
                    or ALL_FIELD_CONFIG_REGISTRY.get("student_extension", {}).get(field_name)
                label_final = label or (field_cfg.get("display_name") if field_cfg else field_name)
                fields.append({
                    "field": field_name,
                    "label": label_final,
                    "is_virtual": False
                })
        return jsonify({"success": True, "fields": fields})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})


